package com.demo.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.demo.repository.FileRepository;
import com.demo.service.BFileService;
import com.demo.util.FileExportUtils;
import com.demo.util.ProperityUtil;
import com.demo.util.StringUtil;
import com.mdx.mobile.commons.verfy.Md5;

@Service
public class BFileServiceImpl implements BFileService{
	
	@Autowired
	private Environment env;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private FileRepository fileRepository;
	@Autowired
	private ProperityUtil properity;
	
	@Override
	public com.demo.domain.File selectByPrimaryKey(String id){
		return fileRepository.findOne(id);
	}
	
	@Override
	public com.demo.domain.File save(com.demo.domain.File f){
		return fileRepository.save(f);
	}
	
	@Override
	public List<Map<String,Object>> selectByFileMd5(String md5){
		String findByIdSql = "select * from b_file where file_md5 = '"+md5+"'";
		return jdbcTemplate.queryForList(findByIdSql);
	}
	
	@Override
	public String uploadFile(byte[] bytes, String fileName, String belong) {
		// TODO Auto-generated method stub
		// 文件保存目录路径
		String savePath = properity.getFile_dir();
    	String md5 = "";
		try {
			md5 = Md5.md5(bytes);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String findByIdSql = "select * from b_file where file_md5 = '"+md5+"'";
		
		 List<Map<String,Object>> lf = jdbcTemplate.queryForList(findByIdSql);
		
		if (lf.size()>0) {
			return lf.get(0).get("file_id").toString();
		}
		long itemsize=bytes.length;
		// 检查文件大小
		if (itemsize >Long.parseLong(properity.getFile_maxsize())) {
			return null;
		}
		// 检查扩展名
		String fileExt = fileName.substring(
				fileName.lastIndexOf(".") + 1).toLowerCase();
		String newFileName = UUID.randomUUID().toString().replace("-", "");
		String minetype = FileExportUtils.getMine(fileName);
		try {
			Calendar cal=Calendar.getInstance();
			String realdir = cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+(cal.get(Calendar.DAY_OF_MONTH))+"/"+minetype.replace("-", "")
					.replace("/", "_");
			File f = new File(savePath, realdir);
			if (!f.isDirectory()) {
				f.mkdirs();
			}
			File uploadedFile = new File(f.getPath(), newFileName + "."+fileExt);
			FileOutputStream fos = new FileOutputStream(uploadedFile);
			fos.write(bytes);
			fos.close();
			com.demo.domain.File ac = new com.demo.domain.File();
			ac.setFileId(StringUtil.getUUID());
			ac.setFileId(newFileName);
			ac.setFileMinitype(minetype);
			ac.setFilePath(realdir + "/" + newFileName + "."+fileExt);
			ac.setFileState(1);
			ac.setFileSize(BigDecimal.valueOf(itemsize));
			ac.setFileMd5(md5);
			ac.setFileCreatetime(new Date());
			ac.setFileName(fileName);
			ac.setFileBelong(belong);
			
			if(FileExportUtils.isImage(fileName)){
				BufferedImage bufferedImage = ImageIO.read(uploadedFile);   
				int width = bufferedImage.getWidth();   
				int height = bufferedImage.getHeight();  
				ac.setFileCreater(width+"x"+height);
			}
			fileRepository.save(ac);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    	return newFileName;

	}
	
	
	

}
